<template>
  <BasicForm @register="registerForm" >
  </BasicForm>

</template>
<script lang="ts" setup>
import { ref, computed, unref, toRaw, useAttrs , watch, onMounted, onUnmounted} from 'vue';
import { BasicForm, useForm, FormSchema } from '/@/components/Form/index';
import { useMessage } from '/@/hooks/web/useMessage';
import { SelectAttributeProps } from "./type";
import { useRuleFormItem } from '/@/hooks/component/useFormItem';
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register','change']);

const attrs = useAttrs()
const props = defineProps(SelectAttributeProps)
const scheme = ref<any[]>([])
const wrapperCol = ref({
  md: { span: 24 },
  sm: { span: 24 },
}) 

const formSchema: FormSchema[] = [
  {
    field: 'name',
    label: '属性名',
    component: 'Select',
    componentProps: () => {
      return {
        placeholder: '请选择',
        showSearch: true
      };
    },
  },
  {
    field: 'values',
    label: '属性值',
    component: 'Select',
    componentProps: () => {
      return {
        placeholder: '请选择',
        showSearch: true
      };
    },
  },
]

const [registerForm, { setProps, resetSchema, resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  wrapperCol: wrapperCol.value,
  labelWidth: 70,
  showActionButtonGroup: false
});

onUnmounted(() => {
  console.log('onUnmounted');
})


onMounted(() => {
  initForm()
})

const initForm = async () => {
  const selectItem = props.selectItem
  const key = selectItem?.id || new Date().getTime()
  // 在同一个组件中用多个baseform会有问题, 这里定义一个随机值
  JSON.parse(JSON.stringify(formSchema)).forEach(e => {
    e.field = e.field + "_" + key
    scheme.value.push(e)
  })
  resetSchema(toRaw(scheme.value))
  await resetFields()

  // 为了使输入框展示 placeholder , 这里需要设置一下空

  const data = {}
  data['name_' + key] =  undefined
  data['values_' + key] = undefined
  setFieldsValue(data)

  updateSchema({
    field: 'name_' + key,
    component: 'Select',
    componentProps: ({ formModel, formActionType }) => {
      return {
        optionFilterProp: "label",
        showSearch: true,
        options: props.attributeOptions,
        onSelect: async (value: any, option: any) => {
          console.log('option', option);
          
          formModel['values_' + key] = undefined
          updateFormSchema(key, option)
        }
      }
    },
  })

  if (props.isUpdate && selectItem.id && selectItem.id !== '') {
    data['name_' + key] =  selectItem.id
    data['values_' + key] = props.selectItem.values?.map(e => JSON.stringify(e))
    console.log('====================data', data)
    setFieldsValue(data)
    updateFormSchema(key, selectItem)
  }
}

const updateFormSchema = (key, selectOption) => {
  console.log('selectOption-attr', key, selectOption);
  
  const options = props?.attributeOptions.filter(e => e.id == selectOption.id)[0].values.map(e => {
    return { label: e.additionalPrice > 0 ? `${e.name} ￥${e.additionalPrice}` : e.name, value: JSON.stringify(e)}
  })
  console.log('options', options)
  updateSchema({
    field: 'values_' + key,
    componentProps: ({ }) => {
      return  {
        mode: 'tags',
        optionFilterProp: "label",
        showSearch: true,
        options,
        onChange: (selectValue: any, _) => {
          console.log('selectValue', selectValue)
          const data = {
            ...props.selectItem,
            id: selectOption.id,
            values: selectValue.map(e => JSON.parse(e)),
            name: selectOption.label
          }
          console.log('data: ', data);
          emit('change', data)
        }
      }
    }
  })
}

</script>

